﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VentaElectrodomesticos.GUI.Base;
using VentaElectrodomesticos.GUI.AbmCliente;
using VentaElectrodomesticos.GUI.Helpers;
using VentaElectrodomesticos.Contrato;
using VentaElectrodomesticos.Negocio;
using VentaElectrodomesticos.Datos;

namespace VentaElectrodomesticos.EfectuarPago
{
    public partial class FormEfectuarPago : BaseEdicion<PagoNegocio, PagoDAO, Pago>
    {
        private static FormEfectuarPago instance;
        private Cliente cliente = new Cliente();
        private Factura factura = new Factura();
        private Decimal? total;
        
        private FacturaNegocio facturaNegocio = new FacturaNegocio();

        public FormEfectuarPago()
        {
            InitializeComponent();
            this.btBuscarCliente.Click += new EventHandler(btBuscarCliente_Click);
            this.Initialize();
            this.Entity = new Pago();
        }

        private void Initialize()
        {
            this.cbProvincia.DataSource = new ProvinciaNegocio().getAll();
            this.cbProvincia.DisplayMember = "Nombre";
            this.cbProvincia.ValueMember = "Id";

            this.cbSucursal.DataSource = new SucursalNegocio().getAll();
            this.cbSucursal.DisplayMember = "Direccion";
            this.cbSucursal.ValueMember = "Id";

            this.cbFacturas.DisplayMember = "Id";
            this.cbFacturas.ValueMember = "Id";

            this.tbCliente.ReadOnly = true;

            this.cbSucursal.SelectedValue = Sesion.getInstance().Usuario.__empleado.Sucursal_Id;
            if (Sesion.getInstance().Usuario.__empleado.Provincia_id != null) {
                this.cbProvincia.SelectedValue = Sesion.getInstance().Usuario.__empleado.Provincia_id;
            }
            
            if (Sesion.getInstance().Usuario.__empleado._Tipo == "Vendedor")
            {
                this.cbProvincia.Enabled = false;
                this.cbSucursal.Enabled = false;
            }
        }

        private void btBuscarCliente_Click(object sender, EventArgs e)
        {
            this.searchCliente();
            this.updateFacturas();
        }

        private void updateFacturas()
        {
            Factura facturaFilter = new Factura();
            facturaFilter.Cliente_Id = this.cliente.Id;
            cbFacturas.DataSource = facturaNegocio.getAll(facturaFilter);
            this.factura = cbFacturas.SelectedItem as Factura;
        }

        private void searchCliente()
        {
            FormAbmCliente formCliente = new FormAbmCliente();
            DialogResult result = GUIHelper.showFormSearch<FormAbmCliente>(formCliente);
            if (result == DialogResult.OK)
            {
                this.tbCliente.Text = formCliente.Entity.Nombre + " " + formCliente.Entity.Apellido;
                this.cliente = formCliente.Entity;
            }
        }

        private void cbFacturas_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.updateCuotas();
        }

        private void updateCuotas()
        {
            int cuotasDeuda = 0;
            cbCuotas.Items.Clear();
            cbCuotas.SelectedText = "";
            this.factura = cbFacturas.SelectedItem as Factura;
            this.factura = this.facturaNegocio.getPagos(this.factura);
            cuotasDeuda = (int)this.factura.Cuotas - (int)this.factura.Pagadas;
            for (int i = 1; i <= cuotasDeuda; i++)
                cbCuotas.Items.Add(i);

            if (cbCuotas.Items.Count > 0)
                this.cbCuotas.SelectedIndex = 0;
        }

        private void cbCuotas_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.updateTotal();
        }

        private void updateTotal()
        {
            int cuotas = Convert.ToInt32(this.cbCuotas.SelectedItem);
            Decimal? montoCuota = this.factura.Total / this.factura.Cuotas;
            this.total = montoCuota * cuotas;
            this.tbTotal.Text = this.total.ToString();
        }

        protected override void getValues()
        {
            this.Entity.Factura_Id = this.factura.Id;
            this.Entity.provincia_id = Convert.ToInt32(cbProvincia.SelectedValue);
            this.Entity.sucursal_id = Convert.ToInt32(cbSucursal.SelectedValue);
            this.Entity.empleado_id = Sesion.getInstance().Usuario.empleado_id;
            this.Entity.fecha = DateTime.Now.ToString(Config.regionTimeFormat);
            this.Entity.monto = this.total;            
        }


        protected override void cumpleValidaciones()
        {
            if (this.factura.Id == null) {
                this.Errores.Add("Debe seleccionar una factura");
            }
            
            if (this.total == null || ! (this.total > 0) ) {
                this.Errores.Add("El monto es invalido");
            }
        }

        internal static FormEfectuarPago getInstance()
        {
            if (instance == null)
                instance = new FormEfectuarPago();
            instance.BringToFront();
            return instance;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            instance = null;
            base.OnClosing(e);
        }
    }
}
